package handler

import (
	"context"
	"errors"
	"fmt"
	"server/basic/dao"
	"server/basic/proto/course"
)

type CourseServer struct {
	course.UnimplementedCourseServerServer
}

func (s *CourseServer) CourseList(_ context.Context, req *course.CourseListReq) (*course.CourseListResp, error) {

	list, err := dao.CourseList(req.Page, req.Size)

	if err != nil {
		return nil, errors.New("课程不存在")
	}
	courselist := []*course.CourseList{}
	for _, courses := range list {
		courselist = append(courselist, &course.CourseList{
			CourseName:        courses.CourseName,
			CourseDescription: courses.CourseDescription,
			CourseUrl:         courses.CourseUrl,
			CourseType:        int64(courses.CourseType),
			CourseSalesVolume: courses.CourseSalesVolume,
			Id:                int64(courses.Id),
		})
	}

	return &course.CourseListResp{List: courselist}, nil
}
func (s *CourseServer) CourseListRecommend(_ context.Context, req *course.CourseListRecommendReq) (*course.CourseListRecommendResp, error) {

	list, err := dao.CourseListRecommend()

	if err != nil {
		return nil, errors.New("课程不存在")
	}
	courselist := []*course.CourseList{}
	for _, courses := range list {
		courselist = append(courselist, &course.CourseList{
			CourseName:        courses.CourseName,
			CourseDescription: courses.CourseDescription,
			CourseUrl:         courses.CourseUrl,
			CourseType:        int64(courses.CourseType),
			CourseSalesVolume: courses.CourseSalesVolume,
			Id:                int64(courses.Id),
		})
	}
	dao.RedisList(list)
	listS, err := dao.RedisListS()
	if err != nil {
		return nil, err
	}
	fmt.Println(listS)
	return &course.CourseListRecommendResp{List: courselist}, nil
}

func (s *CourseServer) CourseUpdate(_ context.Context, req *course.CourseUpdateReq) (*course.CourseUpdateResp, error) {
	long, err := dao.CourseLong()
	if err != nil {
		return nil, err
	}
	sl := len(long)
	if sl < 10 {
		update := dao.CourseUpdate(req.CourseId)

		if update == false {
			return nil, errors.New("修改失败")
		}
	} else {
		return nil, errors.New("推荐课程已满10")
	}

	return &course.CourseUpdateResp{Success: true}, nil
}
